import sa from '../function/global'

var localStorage = {
  get: function (name) {
    return window.localStorage.getItem(name)
  },

  parse: function (name) {
    var storedValue
    try {
      storedValue = JSON.parse(this.get(name)) || null
    } catch (err) {
      sa.log(err)
    }
    return storedValue
  },

  set: function (name, value) {
    window.localStorage.setItem(name, value)
  },

  remove: function (name) {
    window.localStorage.removeItem(name)
  },

  isSupport: function () {
    var supported = true
    try {
      var key = '__sensorsdatasupport__'
      var val = 'testIsSupportStorage'
      this.set(key, val)
      if (this.get(key) !== val) {
        supported = false
      }
      this.remove(key)
    } catch (err) {
      supported = false
    }
    return supported
  }
}

export function getStorageSync(key) {
  return localStorage.parse(key)
}

export function setStorageSync(key, value) {
  var item
  try {
    item = JSON.stringify(value)
  } catch (error) {
    sa.log('序列化缓存对象失败！')
  }
  try {
    localStorage.set(key, item)
  } catch (error) {
    sa.log('set Storage fail!')
  }
}
